/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.shop.service;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.shop.dao.AttributeDao;
import com.thinkgem.jeesite.modules.shop.dao.AttributeItemDao;
import com.thinkgem.jeesite.modules.shop.entity.Attribute;
import com.thinkgem.jeesite.modules.shop.entity.AttributeItem;

/**
 * 商品属性管理Service
 * @author xxs
 * @version 2016-03-03
 */
@Service
@Transactional(readOnly = true)
public class AttributeService extends CrudService<AttributeDao, Attribute> {

	@Autowired
	private AttributeDao attributeDao;
	@Autowired
	private AttributeItemDao attributeItemDao;
	
	public Attribute get(String id) {
		Attribute attribute = super.get(id);
		attribute.setAttributeItemList(attributeItemDao.findList(new AttributeItem(attribute)));
		return attribute;
	}
	
	public List<Attribute> findList(Attribute attribute) {
		return super.findList(attribute);
	}
	public List<Attribute> getAttributeByCategoryId(String category_id) {
		return attributeDao.getAttributeByCategoryId(category_id);
	}
	public List<Attribute> getAttributeListByCategoryId(String category_id) {
		return attributeDao.getAttributeListByCategoryId(category_id);
	}
	
	public Page<Attribute> findPage(Page<Attribute> page, Attribute attribute) {
		return super.findPage(page, attribute);
	}
	
	@Transactional(readOnly = false)
	public void save(Attribute attribute) {
		super.save(attribute);
		for (AttributeItem attributeItem : attribute.getAttributeItemList()){
			if (attributeItem.getId() == null){
				continue;
			}
			if (AttributeItem.DEL_FLAG_NORMAL.equals(attributeItem.getDelFlag())){
				if (StringUtils.isBlank(attributeItem.getId())){
					attributeItem.setShopAttribute(attribute);
					attributeItem.preInsert();
					attributeItemDao.insert(attributeItem);
				}else{
					attributeItem.preUpdate();
					attributeItemDao.update(attributeItem);
				}
			}else{
				attributeItemDao.delete(attributeItem);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Attribute attribute) {
		super.delete(attribute);
		attributeItemDao.delete(new AttributeItem(attribute));
	}
	
	public String toAttributeValue(Attribute attribute, String value) {
		Assert.notNull(attribute);

		if (StringUtils.isEmpty(value) || CollectionUtils.isEmpty(attribute.getAttributeItemList()) || !attribute.getAttributeItemList().contains(value)) {
			return null;
		}
		return value;
	}

	
}